<!doctype html>
<html>
<head>
<script type="text/javascript" src="lib/blockad.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=320, initial-scale=1, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title></title>
<style type="text/css">
body{
	margin:0;
	background-color:#EEE;
	font-size:12px;
}
.item-wrapper,.tz-info-wrapper{
	padding: 5px;
	margin-bottom: 20px;
	background-color: #FFF;
	box-shadow: 0 2px 0 #E2E2E2;
}
.tz-title{
	font-size: 16px;
}
.exclude-div{
	background-color: rgba(100,100,255,0.1);
	padding: 5px 5px;
	margin-bottom: 10px;
	font-size: 15px;
	font-weight: bold;
    color: #777;
}
.wrapper-header{
	display: table;
}
.wrapper-header>div{
	display: table-cell;
}
.preview{
	border:1px solid #EEE;
	vertical-align: middle;
}
.name{
	font-size: 16px;
}
.info{
	padding-left: 10px;
}
.options{
	margin-top: 10px;
}
.preview{
	width: 100px;
	height: 100px;
	font-size: 0;
	text-align: center;
}
.preview img{
	max-width:100%;
	max-height:100%;
}
.price{
	font-size:16px;
}
.now_price{
	color: #F00;
}
.old_price{
	color: #AAA;
}
.selected_opt_tag{
	line-height:30px;
}
.opt{
	display:inline-block;
	margin:5px 4px;
	border:1px solid #DDD;
	line-height:8px;
}
.opt img{
	height:60px;
	width:60px;
	line-height:12px;
}
.opt div{
	min-width:41px;
	height:30px;
	padding: 0 10px;
	text-align: center;
    vertical-align: middle;
    line-height: 30px;
}
.active-opt{
	border-color: black;
	background-color: black;
	color: #FFF;
}
.active-opt div{
	color: #FFF;
}
.count{
	border-top: 1px dashed #DDD;
    margin: 10px 0 5px 0;
    padding-top:10px;
}
.tz-info-wrapper .controls{
	float: right;
}
.tz-count{
	display: table;
	width: 100%;
}
.tz-count>div,.count>div{
	display:table-cell;
	vertical-align:middle;
}
.controls>div{
	display:table-cell;
	vertical-align: middle;
}
.input>input{
	width: 90px;
	height: 30px;
	box-sizing: border-box;
    vertical-align: middle;
    border: 1px solid #DDD;
    border-radius: 0;
	font-size: 18px;
	text-align: center;
	padding: 0;
	-webkit-appearance: none;
}
.input{
	margin:10px 5px;
}
.minus,.plus{
	width: 30px;
	height: 30px;
	margin:10px;
    border: 1px solid #DDD;
    position: relative;
    box-sizing: border-box;
}
.c1,.c2{
	background-color:#999;
	position:absolute;
}
.c1{
	width:20px;
	height:4px;
	top:12px;
	left:4px;
}
.c2{
	width:4px;
	height:20px;
	top:4px;
	left:12px;
}
.count-min{
	padding-left: 10px;
}
.forbid{
	opacity: 0.3;
	cursor: not-allowed;
}
.wrapper-warning{
	font-size: 15px;
	color: #F00;
	background-color: rgba(255,0,0,0.1);
	border-top:1px solid rgba(255,0,0,0.6);
	border-bottom:1px solid rgba(255,0,0,0.6);
	text-align: center;
	padding: 5px 5px;
    margin-bottom: 10px;
}
.hide{
	display: none;
}
.blank{
	height: 44px;
	width: 100%;
}
.bottom-bar{
	position: fixed;
	bottom: 0;
	width: 100%;
	height: 44px;
}
.submit-text{
	color: #FFF;
	width: 100%;
	height: 100%;
	background-color: #B2793D;
	font-size: 15px;
	line-height: 44px;
	text-align: center;
}
.result{
	width:100px;
	height:auto;
	margin:50px auto;
	font-size:18px;
	color:#888;
}
.result img{
	width:100px;
	opacity:0.4;
}
.result div{
	text-align:center;
}
.disable{
	background-color: #999;
}
</style>
</head>
<body>
<?php
//http://www.jajahome.com/furniture/tz_price.php?str=eyJpZCI6MjMsInNldF90eXBlIjoxLCJpdGVtcyI6W3sibWF0X2lkIjoyMTcyLCJmYWJfaWQiOjAsImlkIjo5NTB9LHsibWF0X2lkIjoyMTczLCJmYWJfaWQiOjAsImlkIjo5NjJ9LHsibWF0X2lkIjoyMTczLCJmYWJfaWQiOjAsImlkIjo5NTF9LHsibWF0X2lkIjoyMTcxLCJmYWJfaWQiOjAsImlkIjo5NjF9LHsibWF0X2lkIjoyMTc1LCJmYWJfaWQiOjAsImlkIjo5Njl9LHsibWF0X2lkIjoyMTc4LCJmYWJfaWQiOjAsImlkIjo5NjZ9LHsibWF0X2lkIjoyMjAyLCJmYWJfaWQiOjAsImlkIjo5Njd9LHsibWF0X2lkIjoyMTc2LCJmYWJfaWQiOjAsImlkIjo5NTJ9LHsibWF0X2lkIjoyMTc3LCJmYWJfaWQiOjAsImlkIjo5NjN9LHsibWF0X2lkIjoyMTc3LCJmYWJfaWQiOjAsImlkIjo5NTN9LHsibWF0X2lkIjoyMTg3LCJmYWJfaWQiOjAsImlkIjo5NjV9LHsibWF0X2lkIjoyMjI0LCJmYWJfaWQiOjAsImlkIjo5NDN9LHsibWF0X2lkIjowLCJmYWJfaWQiOjE4MjEsImlkIjo5NDd9LHsibWF0X2lkIjoyMTgyLCJmYWJfaWQiOjAsImlkIjo5NDh9LHsibWF0X2lkIjowLCJmYWJfaWQiOjE4MzgsImlkIjo5NzB9LHsibWF0X2lkIjowLCJmYWJfaWQiOjE3NjIsImlkIjo5NDl9LHsibWF0X2lkIjoyMTU3LCJmYWJfaWQiOjAsImlkIjo5NDF9XSwidHlwZSI6MSwidXNlcl9pZCI6MjAwOSwidXNlcl90b2tlbiI6eyJzaWQiOiIzNzY3MDIiLCJ0b2tlbiI6IjljMDhhN2NlZWFjZjM2N2IzMGE0NzIwOGI4YmQ5MmEwNzUxNDFjIn19
// {
// 	"set_type":1		//1：套装，2：DIY
// 	"id":23,			//套装或DIY的id
// 	"user_id":2010,
// 	"user_token":{"sid":"376702","token":"9c08a7ceeacf367b30a47208b8bd92a075141c"},
// 	"type":2,			//1加入购物车，2直接购买
// 	"items":[
// 		{"id":2659,"fab_id":0,"mat_id":2171},//id为pos表id，材质面料如果未选则值为0
// 		{"id":2660,"fab_id":0,"mat_id":2172},
// 		{"id":2654,"fab_id":0,"mat_id":2168,
// 		{"id":2644,"fab_id":1769,"mat_id":0},
// 		{"id":2691,"fab_id":0,"mat_id":2202}
// 	]
// }
require_once("config/app_webview_config.php");
require_once("app-component.php");
$str=$_GET["str"];
$get_info=base64_decode($str);
$get_info=json_decode($get_info,true);
$user_id=$get_info['user_id'];
$user_token=$get_info['user_token']['token'];

if (!verify($user_id,$user_token)) {
	echo "请重新登录";
	return;
}



//


$user_info=getUserType($user_id);
$user_type = $user_info['user_type'];
$user_type_class=$user_info['user_type_class'];
 
$discount_arr = getUserDiscount($user_type, $user_type_class);
$user_discount = isset($discount_arr[SALES_TYPE_ITEM]['discount'])?$discount_arr[SALES_TYPE_ITEM]['discount']:1;

$set_type=$get_info['set_type'];
$id=$get_info['id'];
$items=getTzDiyCount($get_info['items'],$set_type,$id);

$exclude=array();$j=0;
foreach ($items as $key => $value) {
	if ($value['exclude']) {
		$exclude[$j++]=$value['item_id'];
	}
}
$tz_arr=getTz($id);
$tz_name=$tz_arr['name'];
echo '  <div class="tz-info-wrapper" data-discount="'.$tz_arr['price_custom'].'">
			<div class="tz-title">'.$tz_name.'</div>
			<div class="tz-count">
				<div class="count-name">
			    	套装总数量
			    </div>
			    <div class="controls">
			    	<div><div class="minus"><div class="c1"></div></div></div>
			        <div><div class="input"><input class="c tz-total" type="number" min="1" step="1" value="1" disabled></div></div>
			        <div><div class="plus"><div class="c1"></div><div class="c2"></div></div></div>
			    </div>
			</div>
		</div>';
echo "<script type='text/javascript'>
        var submit_type=".$get_info['type'].";
        var exclude=JSON.parse('".json_encode($exclude)."');
        var beSelect=[];
        var isVip = ".($user_type <= 5 && $user_type >= 3? 'true':'false').";
        var user_discount = parseFloat('".$user_discount."');
      </script>";
function createwrapperHtml($itemObj,$name,$wrapper_id,$price_base,$price_discount,$min,$is_exclude)
{
	global $items;
	echo "<script type='text/javascript'>beSelect['".$wrapper_id."']=[];</script>";
	echo '<div class="item-wrapper'.($is_exclude?" exclude":"").'" id="'.$wrapper_id.'" data-itemid="'.$itemObj->id.'" data-pricebase="'.$price_base.'" data-pricediscount="'.$price_discount.'" data-selpriceid="0">
		'.($is_exclude?'<div class="exclude-div">赠品</div>':'').'
		<div class="wrapper-warning hide">请选择规格</div>
		<div class="wrapper-header">
			<div class="preview"><img src="images/photo_bg.png" class="main_img"></div>
		    <div class="info">
		    	<div class="name">'.$name.'</div>
		    	<div class="price">'.($is_exclude?0:(intval($price_base)?$price_base:"请询价")).'</div>
		        <div class="selected_opt_name">
		        	<div class="sel_fab"></div>
		        	<div class="sel_mat"></div>
		        </div>
		    </div>
		</div>
		<div class="options">';
		foreach ($itemObj->fields as $key => $fields) {
			echo "<div class='fields-wrapper'>";
			echo 	"<div class='fields-name'>".$fields['name']."</div>";
			echo 	"<div class='fields-opts' data-name='".$fields['name']."' data-wrapperid='".$wrapper_id."' data-key='".$key."'>";
					foreach ($fields['objs'] as $opt) {
						echo "<div class='opt' data-id='".$opt['id']."' data-name='".$opt['text']."' data-prime='".$opt['prime']."'>";
						if (isset($opt['url'])&&$opt['url']!=null) {
							echo "<img src='".$opt['url']."' alt='".$opt['text']."'>";
						}
						else{
							echo "<div>".$opt['text']."</div>";
						}
						echo "</div>";
						for ($i=count($items)-1; $i >= 0; $i--) { 
							if ($items[$i]['item_id']==$itemObj->id && (($key=='fab'&&$items[$i]['fab_id']==$opt['id']) || ($key=='mat'&&$items[$i]['mat_id']==$opt['id']))) {
								echo "<script type='text/javascript'>beSelect['".$wrapper_id."']['".$key."']=".$opt['prime'].";</script>";
							}
						}
					}
			echo 	"</div>";
			echo "</div>";
		}
		if ($is_exclude) {
			echo '</div>
					<div class="count">
						<div class="count-name">
					    	数量
					    </div>
					    <div class="count-min">
					    	<div class="c">'.$min.'</div>
					    </div>
					</div>
				</div>';
		}else{
			echo '</div>
					<div class="count">
						<div class="count-name">
					    	数量
					    </div>
					    <div class="controls">
					    	<div><div class="minus"><div class="c1"></div></div></div>
					    	
					        <div><div class="input"><input class="c" type="number" min="'.$min.'" step="1" value="'.$min.'" disabled></div></div>

					        <div><div class="plus"><div class="c1"></div><div class="c2"></div></div></div>
					    </div>
					</div>
				</div>';
		}
}
function createPreviewTableJS($json_arr,$name)
{
	echo "<script type='text/javascript'>";
	echo "previewTable['".$name."']=JSON.parse('".json_encode($json_arr,JSON_UNESCAPED_UNICODE)."')";
	echo "</script>";
}
function createPriceTableJs($json_arr,$name)
{
	echo "<script type='text/javascript'>";
	echo "priceTable['".$name."']=JSON.parse('".json_encode($json_arr,JSON_UNESCAPED_UNICODE)."')";
	echo "</script>";
}
echo "<script type='text/javascript'>var previewTable=[];var priceTable=[];</script>";
foreach ($items as $value) {
	$item=new Item($value['item_id']);
	//print_r($item);
	$wrapper_id='item_'.$value['item_id'].'_'.$value['pos'];
	createwrapperHtml($item,$item->name,$wrapper_id,$item->price_base,$item->price_discount,$value['count'],$value['exclude']);
	createPreviewTableJS($item->previewTable,$wrapper_id);
	createPriceTableJs($item->getPriceTable(),$wrapper_id);
}
?>
<div class="blank"></div>
<div class="bottom-bar">
	<div class="submit-text">确定</div>
</div>
<div id="submit_box" style="display: none">
	<form action="order.php" method="post">
		<input name="obj" type="text" value="">
		<input name="user_id" type="text" value="">
		<input name="user_token" type="text" value="">
	</form>
</div>
<script type="text/javascript">
window.onload=function(){
	var default_img='images/photo_bg.png';
	updateBottombar();
	bindOpt();
	bindCounter();
	autoSelect();
	function updateBottombar() {
		if(!document.querySelector('.item-wrapper'))
		{
			document.querySelector('.submit-text').classList.add('disable');
		}
	}
	function updateWrapperPrice(node)
	{
		var fields_opts_node=node.parentNode;
		if (node.classList.contains('forbid')) {
			return;
		}
		var sel_key=document.querySelector('#'+fields_opts_node.dataset.wrapperid+' .sel_'+fields_opts_node.dataset.key);
		if (fields_opts_node.dataset.key=='fab'||fields_opts_node.dataset.key=='mat') {
			sel_key.textContent=fields_opts_node.dataset.name+':'+node.dataset.name;
		}
		if (node.classList.contains('active-opt')) {
			node.classList.remove('active-opt');
			if (sel_key) {
				sel_key.textContent='';
			}
		}
		else{
			var contain=fields_opts_node;
			var obj=contain.querySelector('.opt.active-opt');
			if (obj) {
				obj.classList.remove('active-opt');
			}
			node.classList.add('active-opt');
		}

		var prime=1,wrapper_id=fields_opts_node.dataset.wrapperid,price;
		var wrapper=document.querySelector('#'+wrapper_id);
		var fields=wrapper.querySelectorAll('.fields-opts');
		var selected_count=fields.length;
		for (var i = fields.length - 1; i >= 0; i--) {
			var selected_opt=fields[i].querySelector('.opt.active-opt');
			if (selected_opt) {
				prime=prime*parseInt(selected_opt.dataset.prime);
				selected_count--;
			}
		}
		//图片显示
		var t=1;
		for (i in previewTable[wrapper_id]){
			if(prime % previewTable[wrapper_id][i]['prime'] == 0)
			{
				wrapper.querySelector('.main_img').src=previewTable[wrapper_id][i]['url'];
				t=0;
				break;
			}
		}
		if (t) {
			wrapper.querySelector('.main_img').src=default_img;
		}
		//价格显示
		t=1;
		for (i in priceTable[wrapper_id]){
			if(priceTable[wrapper_id][i]['prime'] % prime == 0)
			{
				var price_base 		= parseInt(wrapper.dataset.pricebase);
				var price_discount 	= parseFloat(wrapper.dataset.pricediscount);
				var price_custom 	= parseInt(priceTable[wrapper_id][i]['price_custom']);
				var custom_discount = parseFloat(priceTable[wrapper_id][i]['price_discount']);

				var old_price = price_base + price_custom;
				var now_price = 0;
				if (user_discount > 0 && user_discount < 1){
					now_price = ((price_base + price_custom) * user_discount).toFixed(2);
				}else{
					now_price = ((price_base * price_discount + price_custom * custom_discount)).toFixed(2);
				}

				if (wrapper.classList.contains('exclude')){
					now_price = 0;
				}
				
				var vipText = '';
				if (isVip){
					vipText = 'VIP';
				}

				var price_div = wrapper.querySelector('.price');
				//两个折扣都为1则不显示原价
				if(price_discount==1 && custom_discount==1 && user_discount>=1 && !isVip) {
					if (parseInt(now_price)) {
						price_div.innerHTML='<span class="now_price">¥ '+now_price+'</span>';
					}
					else {
						price_div.innerHTML='<span class="now_price">请询价</span>';
					}
				}
				else {
					if (parseInt(now_price)) {
						price_div.innerHTML='<span class="old_price"><del>¥ '+old_price+'</del></span>&nbsp;&nbsp;<span class="now_price">'+ vipText +'¥ '+now_price+'</span>';
					}
					else {
						price_div.innerHTML='<span class="now_price">请询价</span>';
					}
				}
				
				//wrapper.querySelector('.price').textContent=wrapper.classList.contains('exclude')?0:(parseInt(wrapper.dataset.pricebase)?price:'请询价');
				wrapper.dataset.selpriceid=typeof(priceTable[wrapper_id][i]['price_id'])!="undefined"?priceTable[wrapper_id][i]['price_id']:0;
				t=0;
				break;
			}
		}
		if (t) {//如果没有匹配到乘积
			wrapper.dataset.selpriceid=0;
			//price=parseInt(parseInt(wrapper.dataset.pricebase)*parseFloat(wrapper.dataset.pricediscount));
			price=parseInt(parseInt(wrapper.dataset.pricebase));
			//wrapper.querySelector('.price').textContent=wrapper.classList.contains('exclude')?0:(price?price:'请询价');
			wrapper.querySelector('.price').innerHTML = '<span>'+ (wrapper.classList.contains('exclude')?0:(price?'¥ '+price.toFixed(2):'请询价')) +'</span>';
		}else{
			wrapper.querySelector('.wrapper-warning').classList.add('hide');
		}
		//更新SKU显示状态
		for (i = fields.length - 1; i >= 0; i--) {
			var opts=fields[i].querySelectorAll('.opt');
			if (fields[i].querySelector('.active-opt')) {
				var selected_prime=parseInt(fields[i].querySelector('.active-opt').dataset.prime);
			}else{
				var selected_prime=1;
			}
			for (var j = opts.length - 1; j >= 0; j--) {
				if (opts[j].classList.contains('forbid')) {
					opts[j].classList.remove('forbid');
				}
				if(!opts[j].classList.contains('active-opt'))
				{
					var new_prime=prime/selected_prime*parseInt(opts[j].dataset.prime);
					t=1;
					for(var k in priceTable[wrapper_id])
					{
						if (priceTable[wrapper_id][k]['prime']%new_prime==0) {
							t=0;
							break;
						}
					}
					if (t) {
						opts[j].classList.add('forbid')
					}
				}
			}
		}
		return selected_count;
	}
	function autoSelect()
	{
		for (var i in beSelect) {
			for (var j in beSelect[i]) {
				if (beSelect[i][j]) {
					var node=document.querySelector('#'+i+' .opt[data-prime="'+beSelect[i][j]+'"]');
					updateWrapperPrice(node);
				}
			}
		}
	}
	//绑定opt
	function bindOpt()
	{
		var opts=document.querySelectorAll('.opt');
		for (var i = opts.length - 1; i >= 0; i--) {
			opts[i].addEventListener('click',function(){
				updateWrapperPrice(this);
			});
		}
	}
	//绑定计数器
	function bindCounter()
	{
		controls1=document.querySelectorAll('.minus,.plus');
		controls2=document.querySelectorAll('.c');
		for (var i = controls1.length - 1; i >= 0; i--) {
			controls1[i].addEventListener('click',function(){
				var c=this.parentNode.parentNode.querySelector('.c');
				if (this.classList.contains('minus')) {
					changeCount('m',c);
				}
				else if(this.classList.contains('plus')){
					changeCount('a',c);
				}
			});
		}
		for (var i = controls2.length - 1; i >= 0; i--) {
			controls2[i].addEventListener('change',function(){
				changeCount(this.value,this);
			});
		}
	}
	function changeCount(value,c)
	{
		var min_value=parseInt(c.min);
		if(value=="a")
		{
			if(parseInt(c.value)<min_value)
			{
				c.value=min_value;
			}
			c.value=parseInt(c.value)+1;
		}
		else if(value=="m")
		{
			if(parseInt(c.value)>min_value)
			{
				c.value=parseInt(c.value)-1;
			}
			else
			{
				c.value=min_value;
			}
		}
		else
		{
			c.value=parseInt(value)>min_value?parseInt(value):min_value;
		}
	}
	if (document.querySelector('.submit-text:not(.disable)')) {
		document.querySelector('.submit-text:not(.disable)').addEventListener('click',submit);
	}
	function submit()
	{
		var fields_opts=document.querySelectorAll('.fields-opts');
		var t=0,count,j;
		for (var i = fields_opts.length - 1; i >= 0; i--) {
			if(!fields_opts[i].querySelector('.opt.active-opt')){
				document.querySelector("#"+fields_opts[i].dataset.wrapperid+" .wrapper-warning").classList.remove('hide');
				location.href=location.href.split('#')[0]+"#"+fields_opts[i].dataset.wrapperid;
				t=1;
			}
		}
		if (t) {
			return;
		}
		var post_order={};
		post_order['tz']=[];
		post_order['tz'][0]={};
		post_order['tz'][0]['info']={};
		post_order['tz'][0]['items']=[];
		post_order['tz'][0]['info']['id']=parseInt(<?= $id?>);
		post_order['tz'][0]['info']['cart_type']=1;
		post_order['tz'][0]['info']['count']=parseInt(document.querySelector('.tz-total').value);
		post_order['tz'][0]['info']['discount']=parseFloat(document.querySelector('.tz-info-wrapper').dataset.discount);
		<?php
		if (!empty($exclude)) {
			echo "post_order['tz'][0]['info']['exclude']=JSON.parse('".json_encode($exclude)."');";
		}
		?>
		var wrapper=document.querySelectorAll('.item-wrapper');
		for (i = wrapper.length - 1; i >= 0; i--) {
			post_order['tz'][0]['items'][i]={};
			count=wrapper[i].querySelector('.c');
			post_order['tz'][0]['items'][i]["count"]=parseInt(count.value?count.value:count.textContent);
			post_order['tz'][0]['items'][i]["item_id"]=parseInt(wrapper[i].dataset.itemid);
			post_order['tz'][0]['items'][i]["price_id"]=parseInt(wrapper[i].dataset.selpriceid);
			post_order['tz'][0]['items'][i]["sku_id"]={};
			fields_opts=wrapper[i].querySelectorAll('.fields-opts');
			
			for (j=0;j<fields_opts.length;j++) {
				post_order['tz'][0]['items'][i]['sku_id'][fields_opts[j].dataset.key]=fields_opts[j].querySelector('.opt.active-opt').dataset.id;
			}
		}
		if (submit_type==2) {//直接购买
			post_order['tz'][0]['info']['cart_id']=0;
			document.querySelector('#submit_box input[name="obj"]').value=JSON.stringify(post_order);
			document.querySelector('#submit_box input[name="user_id"]').value=<?= $user_id?>;
			document.querySelector('#submit_box input[name="user_token"]').value=<?= "'".$user_token."'"?>;
			document.querySelector('#submit_box>form').submit();
		}
		else if(submit_type==1){//添加到购物车
			var fd=new FormData();
			fd.append("q","submitShopingCart");
			fd.append("order",JSON.stringify(post_order['tz'][0]));
			fd.append("type",<?= $set_type?>);
			fd.append("user_id",<?= $user_id?>);
			fd.append("user_token",<?= "'".$user_token."'"?>);

			xhr=new XMLHttpRequest();
			xhr.onreadystatechange = function(){
			  if (xhr.readyState === 4&&xhr.status === 200){
			   if(parseInt(xhr.responseText))
			   {
			   		html="<div class=\"result\"><div><img src=\"images/success.png\"></div><div>提交成功</div></div>";
				   	setTimeout('location.href="webView://close"',1500);
			   }
			   else
			   {
				   html="<div class='result'><div><img src='images/failed.png'></div><div>提交失败<br>重新选择</div></div>";
				   setTimeout('history.back()',1500);
			   }
			   document.body.innerHTML=html;
			  }
			};
			xhr.onerror = function (e) {
			  console.error(xhr.statusText);
			};
			xhr.open("post","calc.php", true);
			xhr.send(fd);	
		}
	}
}
</script>
</body>
</html>
